<template>
  <el-tree-select
    v-model="pageData[node.name]"
    multiple
    :data="treeData"
    :props="treeProps"
    :render-after-expand="false"
    :disabled="inputDisabled"
    :placeholder="placeholder"
    :default-expanded-keys="expandedData"
    :expand-on-click-node="false"
    show-checkbox
    filterable
    check-on-click-node
    style="width: 100%"
  />
</template>

<script setup>
import { ref, onMounted, inject, getCurrentInstance, nextTick } from 'vue';
import { useDisabled } from 'element-plus';
import { getEmployee } from '@/utils/system';
import tool from "@/utils/tool";
import EventHandler from "@/visual/js/event";
import visual from "@/visual/js/visual";

const props = defineProps({
  node: Object
});
const initializing = ref(true);
const pageData = inject("pageData", ref({}));
const currNode = ref(props.node);
const inputDisabled = useDisabled();
const expandedData = ref([]);
const treeData = ref([]);
const treeProps = ref({
  children: "children",
  label: function (data) {
    return data.text;
  }
});

const placeholder = ref('');
const multiple = ref(false);
const clearable = ref(false);
const eventHandler = new EventHandler(
  inject('eventHandler', Function, true),
  getCurrentInstance(),
  currNode.value
);

const init = (styleId) => {
  initializing.value = true;
  visual.initStyle(currNode.value, styleId);
  const compStyle = currNode.value.currCompStyle || {};

  placeholder.value = compStyle['placeholder'] || '--请选择--';
  multiple.value = compStyle['multiple'] || false;
  clearable.value = compStyle['clearable'] || false;

  const defaultValue = visual.loadDefaultValue(currNode.value, eventHandler) || '';
  if (multiple.value) {
    pageData.value[props.node.name] = defaultValue;
  } else {
    pageData.value[props.node.name] = defaultValue.split(",")[0];
  }

  if (!pageData.value[props.node.name]) {
    pageData.value[props.node.name] = '';
  }

  nextTick(() => initializing.value = false);
};

const loadTree = async() => {
  treeData.value = await getEmployee();
  tool.walkTree({children: treeData.value}, (node) => {
    node.value = node.id;
    node.label = node.text;
  });

  if (treeData.value && treeData.value.length === 1) {
    expandedData.value = [treeData.value[0].id];
  }
};

onMounted(() => {
  init();
  loadTree();
});
</script>